<template>
	<view class="apply-detail">
		<view class="apply-detail-list">
			<!-- <view class="apply-tips">* 店端若需参加集训，参加人数为3人，总经理或副总经理必须参加，其余岗位为服务经理、客服经理</view> -->
			<view class="create-item">
				<text class="info-item-title">报名站点</text>
				<input class="info-item-input" type="text" @click="handleOpenSitePopup"
					placeholder-class="placeholderFontClass" disabled readonly placeholder="请选择报名站点" v-model="signSite">
				<uni-icons class="right-arrow-icon" type="forward" size="14" color="#999"></uni-icons>
			</view>

			<view class="create-item">
				<text class="info-item-title">店代码</text>
				<input class="info-item-input" type="text" disabled placeholder-class="placeholderFontClass"
					placeholder="请输入店代码" v-model="shopId">
			</view>
			<view class="create-item">
				<text class="info-item-title">参训人电话</text>
				<input class="info-item-input" type="text" placeholder-class="placeholderFontClass"
					placeholder="请输入参训人电话" v-model="phone">
			</view>
			<!-- <view class="create-item">
				<text class="info-item-title">店名称</text>
				<input class="info-item-input" type="text" placeholder-class="placeholderFontClass" placeholder="请输入店名称"
					v-model="shopName">
			</view> -->
			<view class="apply-detail-item" v-for="(item, index) in applyWriteList" :key="index">
				<view class="item-title">
					<text class="item-title-left">参训人员{{index + 1}}</text>
					<!-- <text class="delete-text" @click="handleDeletePerson(item, index)" v-show="index > 0">删除</text> -->
					<van-icon class="delete-icon" @click="handleDeletePerson(item, index)" v-show="index > 0"
						name="delete-o" />
				</view>
				<view class="item-form">
					<view class="create-item">
						<text class="info-item-title">姓名</text>
						<input class="info-item-input" type="text" placeholder-class="placeholderFontClass"
							placeholder="请输入姓名" v-model="item.name">
					</view>
					<view class="create-item">
						<text class="info-item-title">岗位</text>
						<input class="info-item-input" type="text" @click="handleOpenRolePopup(index)"
							placeholder-class="placeholderFontClass" disabled readonly placeholder="请选择职位"
							v-model="item.role">
						<uni-icons class="right-arrow-icon" type="forward" size="14" color="#999"></uni-icons>
					</view>
					<!-- <view class="create-item">
						<text class="info-item-title">联系电话</text>
						<input class="info-item-input" type="text" maxlength="11"
							placeholder-class="placeholderFontClass" placeholder="请输入联系电话" v-model="item.tel">
					</view> -->
				</view>
			</view>

			<!-- <button class="add-btn" @click.stop.prevent="handleAddPerson">添加参训人员</button> -->
			<button class="submit-btn" @click.stop.prevent="handleSubmit">提交</button>
			<button class="cancel-btn" @click.stop.prevent="handleCancelSignUp">取消报名</button>
			<view class="overflow-height"></view>
		</view>

		<!-- 职位popup -->
		<van-popup :show="rolePopShow" position="bottom">
			<van-picker show-toolbar :columns="roleNameList" @confirm="onRoleConfirm" @cancel="rolePopShow = false" />
		</van-popup>

		<van-popup :show="fixedRolePopShow" position="bottom">
			<van-picker show-toolbar :columns="fixedRoleNameList" @confirm="onFixedRoleConfirm"
				@cancel="fixedRolePopShow = false" />
		</van-popup>

		<!-- 报名站点列表 -->
		<van-popup :show="sitePopShow" position="bottom">
			<van-picker show-toolbar :columns="siteNameList" value-key="name" :default-index="selectedIndex"
				@confirm="onSiteConfirm" @cancel="sitePopShow = false" />
		</van-popup>


		<!-- 进群二维码modal -->
		<view class="group-qrcode-mask" v-show="isGroupQrcodeShow">
			<view class="group-qrcode-bg">
				<view class="text">报名成功，赶快加入培训群吧！</view>
				<view class="img">
					<image class="qrcode-img" show-menu-by-longpress :src="curGroupQrcode" mode="aspectFit"></image>
				</view>
			</view>

			<uni-icons class="close-icon" type="close" size="36" color="#f2f2f2" @click="closeQrcodeMask"></uni-icons>
		</view>
	</view>
</template>

<script>
	import apiRqs from "@/api/api-request.js";
	import getDateTime from '@/common/getDateTime.js';
	export default {
		data() {
			return {
				userOpenid: "",
				applyList: {},
				curApplyId: "",
				rolePopShow: false,
				fixedRolePopShow: false,
				currentIndex: -1,
				roleNameList: ['服务经理', '客服经理', '前台主管', '服务顾问', '客服专员'],
				fixedRoleNameList: ['总经理', '副总经理'],
				shopId: "",
				phone: "",
				// shopName: "",
				deleteIdList: [],
				applyWriteList: [],
				isGroupQrcodeShow: true,
				curGroupQrcode: "",
				signSite: "",
				sitePopShow: false,
				siteNameList: [],
				selectedIndex: 0,
				isEdit: false,
			}
		},
		onShow() {
			getApp().showLoading();
			const alreayApplyInfo = uni.getStorageSync("alreayApplyInfo");
			this.curGroupQrcode = alreayApplyInfo.qrCode ? alreayApplyInfo.qrCode : "";
			if (alreayApplyInfo) {
				this.applyWriteList = alreayApplyInfo.courseSignUps;
				this.applyList = alreayApplyInfo;
				this.curApplyId = alreayApplyInfo.id;
				this.shopId = alreayApplyInfo.courseSignUps[0].shopId;
				this.phone = alreayApplyInfo.courseSignUps[0].tel;
			}
			setTimeout(() => {
				uni.hideLoading();
			}, 1000)
		},
		onLoad(option) {
			this.getSignSiteList();
			this.userOpenid = option.openid;
		},
		methods: {
			handleOpenRolePopup(index) {
				if (index == 0) {
					this.fixedRolePopShow = true;
				} else {
					this.rolePopShow = true;
				}
				this.currentIndex = index;
			},
			onRoleConfirm(value) {
				console.log(value);
				this.applyWriteList[this.currentIndex].role = value.detail.value;
				this.rolePopShow = false;
			},
			onFixedRoleConfirm(value) {
				this.applyWriteList[this.currentIndex].role = value.detail.value;
				this.fixedRolePopShow = false;
			},
			handleAddPerson() {
				this.applyWriteList.push({
					"id": "0",
					"name": "",
					"shopId": "",
					"role": "",
					"tel": "00000000000",
					"state": "0",
					"courseId": "",
					"softDelete": false,
					"createTime": "",
					"openId": ""
				})
			},
			handleDeletePerson(item, index) {
				// getApp().showLoading();
				// let rqs = {
				// 	id: item.id
				// };
				this.deleteIdList.push(item.id);
				this.applyWriteList.splice(index, 1);


			},
			async handleSubmit() {
				let timeStr = getDateTime.dateTimeStr('y-m-d h:i:s');
				let applyWriteList = this.applyWriteList;
				let curApplyId = this.curApplyId; // 当前选中的报名id
				let canSubmit = true;
				let reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
				if (this.shopId.trim() == "") {
					getApp().showToast("店代码不能为空");
					canSubmit = false;
				} else if (this.phone.trim() == "") {
					getApp().showToast(`联系电话不能为空`);
					canSubmit = false;
				} else if (!reg.test(this.phone)) {
					getApp().showToast(`联系电话格式错误`);
					canSubmit = false;
				} else {
					applyWriteList[0].tel = this.phone;
					for (let i = 0; i < applyWriteList.length; i++) {
						applyWriteList[i].courseId = curApplyId;
						applyWriteList[i].createTime = timeStr;
						applyWriteList[i].openId = this.userOpenid;
						applyWriteList[i].shopId = this.shopId;
						if (applyWriteList[i].name.trim() == "") {
							getApp().showToast(`参训人员${i + 1}的姓名不能为空`);
							canSubmit = false;
						} else if (applyWriteList[i].role == "") {
							getApp().showToast(`参训人员${i + 1}的岗位不能为空`);
							canSubmit = false;
						}
						// else if (applyWriteList[i].tel.trim() == "") {
						// 	getApp().showToast(`参训人员${i + 1}的联系电话不能为空`);
						// 	canSubmit = false;
						// }
					}
					if (canSubmit) {
						console.log('提交修改后的数据', this.applyWriteList);
						getApp().showLoading();
						let idList = this.deleteIdList;
						if (idList.length > 0) {
							for (let i = 0; i < idList.length; i++) {
								await apiRqs._deleteAlreadyApplyPerson(idList[i]).then((res) => {
									if (res.code == 2) {
										console.log('删除成功');
									}
								}).catch((err) => {
									console.log('err', err);
								})
							}
						}


						await apiRqs._editAlreadyApplyInfo(this.applyWriteList).then((res) => {
							console.log('提交结果', res);
							uni.hideLoading();
							if (res.code == 200) {
								getApp().showToast("提交成功", "success");
								// 拿到修改成功之后的courseId与报名列表进行匹配，取出修改后的报名进群图片
								for (let i = 0; i < this.siteNameList.length; i++) {
									if (this.applyWriteList[0].courseId === this.siteNameList[i].id) {
										this.curGroupQrcode = this.siteNameList[i].qrCode;
									}
								}
								// setTimeout(() => {
								// 	uni.navigateBack();
								// }, 1500)
								this.isEdit = true;
								this.isGroupQrcodeShow = true;
							} else {
								getApp().showToast(res.msg);
							}
						}).catch((err) => {
							console.log('err', err);
						})
					}
				}
			},
			closeQrcodeMask() {
				this.isGroupQrcodeShow = false;
				if (this.isEdit) {
					uni.navigateBack();
				}
			},
			// 获取报名站点
			getSignSiteList() {
				var that = this;
				let rqs = {
					"pageSize": 9999,
					"pageIndex": 1,
					"orderBy": "asc"
				};
				apiRqs._getApplyList(rqs).then((res) => {
					console.log('报名列表', res);
					if (res.code == 200) {
						let applyData = JSON.parse(JSON.stringify(res.data.data));
						// let newList = [];
						for (let i = 0; i < applyData.length; i++) {
							if (that.applyList.id == applyData[i].id) {
								that.selectedIndex = i;
								that.signSite = applyData[i].name;
							}
						}
						that.siteNameList = applyData;
					} else {
						getApp().showToast(res.msg);
					}
				}).catch((err) => {
					console.log('err', err);
				})
			},
			// 打开站点popup
			handleOpenSitePopup() {
				this.sitePopShow = true;
			},
			// 确认站点popup选择
			onSiteConfirm(value) {
				console.log(value);
				if (value.detail.value.largestNum == value.detail.value.signUpNum) {
					return getApp().showToast("当前站点人数已报满，请另选站点报名");
				} else {
					this.signSite = value.detail.value.name;
					this.curApplyId = value.detail.value.id;
					this.sitePopShow = false;
				}
			},
			// 取消报名
			handleCancelSignUp() {
				const that = this;
				let rqs = [];
				for (let i = 0; i < that.applyWriteList.length; i++) {
					rqs.push(that.applyWriteList[i].id);
				}
				uni.showModal({
					title: '提示',
					content: '确认取消报名？',
					success: function(res) {
						if (res.confirm) {
							getApp().showLoading();
							apiRqs._cancelSignUp(rqs).then((res) => {
								uni.hideLoading();
								console.log('取消报名结果', res);
								if (res.code == 200) {
									getApp().showToast("取消成功");
									setTimeout(() => {
										uni.navigateBack();
									}, 1500)
								} else {
									getApp().showToast(res.msg);
								}
							}).catch((err) => {
								uni.hideLoading();
								console.log('err', err);
							})
						}
					}
				});

			},
		},
	}
</script>

<style lang="less">
	page {
		background-color: #f5f5f5;
	}

	.apply-detail {
		.apply-detail-list {
			.add-btn {
				margin: 20px 15px;
				background-color: transparent;
				border: 1px solid #008aff;
				color: #008aff;
				font-size: 15px;
				height: 35pt;
				line-height: 35pt;
			}

			.submit-btn {
				margin: 20px 15px;
				border: none;
				background-color: #008aff;
				color: #fff;
				font-size: 15px;
				height: 35pt;
				line-height: 35pt;

				&:active {
					background-color: #0076DB;
				}
			}

			.cancel-btn {
				margin: 20px 15px;
				border: none;
				background-color: #ee0a24;
				color: #fff;
				font-size: 15px;
				height: 35pt;
				line-height: 35pt;
			}

			.overflow-height {
				height: 20px;
			}

			.apply-tips {
				font-size: 12px;
				color: #999;
				margin: 10px;
			}

			.apply-detail-item {
				.item-title {
					margin: 10px 15px;
					font-size: 14px;
					color: #333;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.delete-text {
						color: #999;
					}

					.delete-icon {
						font-size: 16px;
						color: #999;
					}
				}
			}

			.create-item {
				display: flex;
				align-items: center;
				width: 100%;
				height: 48px;
				line-height: 48px;
				border-bottom: 1px solid #f5f5f5;
				background-color: #fff;
				padding: 0 15px;
				box-sizing: border-box;
				position: relative;

				.right-arrow-icon {
					position: absolute;
					right: 10px;
				}

				&:first-child {
					border-top: 1px solid #f5f5f5;
				}

				.info-item-title {
					width: 80px;
					flex: 0 0 80px;
					font-size: 14px;
				}

				.info-item-input {
					flex: 1;
					font-size: 14px;
					text-align: left;
					color: #666666;
				}

				.placeholderFontClass {
					color: #ddd;
				}
			}
		}

		.group-qrcode-mask {
			position: fixed;
			top: 0;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: rgba(0, 0, 0, 0.5);
			z-index: 9999;

			.group-qrcode-bg {
				position: absolute;
				top: 10%;
				height: 60%;
				left: 20px;
				right: 20px;
				background-color: #fff;
				border-radius: 6px;
				padding: 8px;
				box-sizing: border-box;

				.text {
					font-size: 14px;
					color: #666;
					font-weight: 500;
					text-align: center;
					margin-top: 12px;
				}

				.img {
					width: 100%;
					height: 90%;

					.qrcode-img {
						width: 100%;
						height: 100%;
					}
				}
			}

			.close-icon {
				position: absolute;
				top: calc(70% + 20px);
				left: 50%;
				margin-left: -18px;
			}
		}
	}
</style>